package com.amigo.online.provider.user.config;

import com.amigo.online.provider.user.config.bean.JsonObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.amigo.online.provider.user.interceptor.TokenInterceptor;

import java.util.List;

@Configuration
public class AmigoOnlineProviderUserAuthConfiguration extends WebMvcConfigurationSupport {

    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter(){
        MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter();
        JsonObjectMapper jsonObjectMapper = new JsonObjectMapper();
        converter.setObjectMapper(jsonObjectMapper);
        return converter;
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (int i = 0; i<converters.size(); i++){
            if(converters.get(i) instanceof MappingJackson2HttpMessageConverter){
                converters.remove(i);
            }
        }
        converters.add(getMappingJackson2HttpMessageConverter());
        System.out.println("=======================加载自定义处理器configureMessageConverters====================");
    }





    @Bean
    public TokenInterceptor getTokenInterceptor() {
        return new TokenInterceptor();
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration ir = registry.addInterceptor(getTokenInterceptor());
        ir.addPathPatterns("/**");
        ir.excludePathPatterns("/user/getAll/**");
        ir.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        ir.excludePathPatterns("/error/**", "/error");

    }
    /**
     * 加上swagger的地址
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

    }

}
